import json
from flask import request
from werkzeug.exceptions import HTTPException


class APIException(HTTPException):
    code = 500   # 这个code是大方向
    message = 'sorry, 一个未知错误'  # 这个是错误信息
    error_code = 999   # 这个是在大方向code下的详细错误代码

    def __init__(self, message=None, code=None, error_code=None, headers=None):
        if code:
            self.code = code
        if message:
            self.message = message
        if error_code:
            self.error_code = error_code
        super(APIException, self).__init__(message, None)

    def get_body(self,environ=None,scope=None,):
        body = dict(
            message = self.message,
            error_code = self.error_code,
            request = request.method + ' ' + self.get_url_no_param()
        )
        text = json.dumps(body)
        return text

    def get_headers(self,environ= None,scope= None):
        return [("Content-Type", "application/json; charset=utf-8")]


    @staticmethod
    def get_url_no_param():
        full_path = str(request.full_path)
        main_path = full_path.split('?')
        return main_path[0]
